<?php

namespace App;

use App\Exception\MethodArgumentNotValidException;
use Wonfu\Core\ExceptionHandlerInterface;
use Wonfu\Http\ServerResponse;

class ExceptionHandler implements ExceptionHandlerInterface
{
    public function dispatch(\Throwable $exception)
    {
        if ($exception instanceof \App\Exception\MethodArgumentNotValidException) {
            return $this->methodArgumentNotValidExceptionHandler($exception);
        }
        $response = new ServerResponse();
        $response->setStatusCode(200);
        $response->setContent(json_encode([
            'ret' => 1,
            'msg' => $exception->getMessage(),
            'data' => $exception->getTraceAsString(),
            'line' => $exception->getFile() . ' ' . $exception->getLine(),
        ]));
        $response->send();
        return 0;
    }

    public function methodArgumentNotValidExceptionHandler(MethodArgumentNotValidException $exception)
    {

        $response = new ServerResponse();
        $response->setStatusCode(200);
        $response->setContent(json_encode([
            'ret' => 1,
            'msg' => $exception->getErrors()->get(0)->getMessage()
        ]));
        $response->send();
        return 0;
    }

}